package com.tarzan.cms.modules.api;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tarzan.cms.modules.admin.model.biz.Article;
import com.tarzan.cms.modules.admin.service.biz.*;
import com.tarzan.cms.modules.admin.vo.ArticleConditionVo;
import com.tarzan.cms.utils.*;
import com.tarzan.cms.modules.admin.model.biz.Comment;
import com.tarzan.cms.modules.admin.model.biz.Love;
import com.tarzan.cms.modules.admin.vo.base.ResponseVo;
import com.tarzan.cms.common.constant.CoreConst;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.List;

/**
 * 给前台页面提供的接口，包括针对文章进行的添加评论、获取评论、增加浏览次数和点赞操作
 *
 * @author tarzan liu
 * @since JDK1.8
 * @date 2021年5月11日
 */
@Slf4j
@RestController
@Api(value = "tarzan-cms-api", tags = "泰山cms内容管理系统api")
@RequestMapping("blog/api")
@AllArgsConstructor
public class CmsApiController {

    private final ArticleService articleService;
    private final CommentService commentService;
    private final LoveService loveService;
    private final CategoryService categoryService;
    private final TagsService tagsService;

    @ApiOperation(value = "文章列表-分页")
    @GetMapping("/articles")
    public ResponseVo getArticles(Integer pageNumber, Integer pageSize,ArticleConditionVo param) {
        IPage<Article> page = new Page<>(pageNumber, pageSize);
        List<Article> articleList = articleService.findByCondition(page, param);
        long total=articleService.lambdaQuery().eq(Article::getStatus,CoreConst.STATUS_VALID).count();
        page.setRecords(articleList);
        page.setTotal(total);
        return ResultUtil.vo(page);
    }

    @ApiOperation(value = "热门文章")
    @GetMapping("/hot/articles")
    public ResponseVo hot(Integer size) {
        if(size>CoreConst.PAGE_SIZE){
            size=CoreConst.PAGE_SIZE;
        }
        return ResultUtil.vo(articleService.hotList(size));
    }

    @ApiOperation(value = "最新文章")
    @GetMapping("/recent/articles")
    public ResponseVo recent(Integer size) {
        if(size>CoreConst.PAGE_SIZE){
            size=CoreConst.PAGE_SIZE;
        }
        return ResultUtil.vo(articleService.recentList(size));
    }

    @ApiOperation(value = "猜测你喜欢")
    @GetMapping("/random/articles")
    public ResponseVo random(Integer size) {
        if(size>CoreConst.PAGE_SIZE){
            size=CoreConst.PAGE_SIZE;
        }
        return ResultUtil.vo(articleService.randomList(size));
    }

    @ApiOperation(value = "文章详情")
    @GetMapping("/article/detail")
    public ResponseVo article(Integer articleId) {
        return ResultUtil.vo(articleService.readById(articleId));
    }

    @ApiOperation(value = "分类列表")
    @GetMapping("/category/list")
    public ResponseVo categoryList() {
        return ResultUtil.vo(categoryService.selectCategories(CoreConst.STATUS_VALID));
    }

    @ApiOperation(value = "分类列表")
    @GetMapping("/tag/list")
    public ResponseVo tagList() {
        return ResultUtil.vo(tagsService.list());
    }

    @GetMapping("/diary")
    public ResponseVo diary() {
        return ResultUtil.vo(articleService.timeline());
    }

    @ApiOperation(value = "评论列表-分页")
    @PostMapping("comments")
    public IPage<Comment> getComments(Integer sid, Integer pageNumber, Integer pageSize) {
        return commentService.commentsBySid(sid, pageNumber, pageSize);
    }

    @ApiOperation(value = "评论保存")
    @PostMapping("comment/save")
    public ResponseVo saveComment(HttpServletRequest request, Comment comment) throws UnsupportedEncodingException {
        if (StringUtils.isEmpty(comment.getNickname())) {
            return ResultUtil.error("请输入昵称");
        }
        String content = comment.getContent();
        if (!XssKillerUtil.isValid(content)) {
            return ResultUtil.error("内容不合法");
        }
        content = XssKillerUtil.clean(content.trim()).replaceAll("(<p><br></p>)|(<p></p>)", "");
        comment.setContent(content);
        comment.setIp(IpUtil.getIpAddr(request));
        if (StringUtils.isNotBlank(comment.getQq())) {
            comment.setAvatar("http://q1.qlogo.cn/g?b=qq&nk=" + comment.getQq() + "&s=100");
        } else if (StringUtils.isNotBlank(comment.getEmail())) {
            String entry = null;
            try {
                entry = MD5Util.md5Hex(comment.getEmail());
            } catch (NoSuchAlgorithmException e) {
                log.error("MD5出现异常{}", e.getMessage(), e);
            }
            comment.setAvatar("http://www.atoolbox.net/" + entry );
        }
        boolean a = commentService.insertComment(comment);
        if (a) {
            return ResultUtil.success("评论提交成功,系统正在审核");
        } else {
            return ResultUtil.error("评论提交失败");
        }
    }


    @ApiOperation(value = "点赞")
    @PostMapping("love")
    public ResponseVo love(HttpServletRequest request, Integer bizId, Integer bizType) {
        Date date = new Date();
        String ip = IpUtil.getIpAddr(request);
        Love love = loveService.checkLove(bizId, ip);
        if (love == null) {
            love = new Love();
            love.setBizId(bizId);
            love.setBizType(bizType);
            love.setUserIp(ip);
            love.setStatus(CoreConst.STATUS_VALID);
            love.setCreateTime(date);
            love.setUpdateTime(date);
            loveService.save(love);
            return ResultUtil.success("点赞成功");
        } else {
            return ResultUtil.error("您已赞过了哦~");
        }
    }

}
